package com.xnx3.wangmarket.plugin.bbs.controller;

import java.awt.Font;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.DateUtil;
import com.xnx3.Lang;
import com.xnx3.StringUtil;
import com.xnx3.exception.NotReturnValueException;
import com.xnx3.j2ee.Func;
import com.xnx3.j2ee.Global;
import com.xnx3.j2ee.entity.SmsLog;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.func.ActionLogCache;
import com.xnx3.j2ee.func.AttachmentFile;
import com.xnx3.j2ee.func.Captcha;
import com.xnx3.j2ee.func.Log;
import com.xnx3.j2ee.service.SmsLogService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.shiro.ShiroFunc;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.media.CaptchaUtil;
import com.xnx3.wangmarket.admin.G;
import com.xnx3.wangmarket.admin.bean.UserBean;
import com.xnx3.wangmarket.admin.entity.Site;
import com.xnx3.wangmarket.admin.util.AliyunLog;
import com.xnx3.wangmarket.admin.vo.SiteVO;
import com.xnx3.wangmarket.plugin.bbs.entity.SystemSet;
import com.xnx3.wangmarket.plugin.bbs.util.Action;
import com.xnx3.wangmarket.superadmin.entity.Agency;

/**
 * 论坛登录、注册
 * @author 管雷鸣
 */
@Controller
@RequestMapping("/plugin/bbs/")
public class LoginBbsPluginController extends BBSBaseController {
	@Resource
	private UserService userService;
	@Resource
	private SmsLogService smsLogService;
	@Resource
	private SqlService sqlService;
	
	

	/**
	 * 注册页面 
	 */
	@RequestMapping("/reg${url.suffix}")
	public String reg(HttpServletRequest request ,Model model){
//		if(Global.getInt("ALLOW_USER_REG") == 0){
//			return error(model, "系统已禁止用户自行注册");
//		}
//		//判断用户是否已注册，已注册的用户将出现提示，已登录，无需注册
		if(getUser() != null){
			return error(model, "您已登陆，无需注册", "plugin/bbs/list.do?siteid="+request.getParameter("siteid"));
		}
		
		userService.regInit(request);
		ActionLogCache.insert(request, "进入论坛注册页面");
		modelSet(request, model);
		return "plugin/bbs/reg";
	}
	
	

	/**
	 * 用户开通账户并创建网站，进行提交保存
	 * @param username 用户名
	 * @param email 邮箱，可为空
	 * @param password 密码
	 * @param siteid 跟随传第参数，此论坛是属于那个站点，必填，不会为空
	 * @param classid 分类id，来源是哪个板块，可为空
	 * @param postid 帖子id，来源是哪个帖子详情页面，可为空
	 * @return 成功后，info会返回跳转的链接地址，如： plugin/bbs/view.do?id=123
	 */
	@RequestMapping(value="regSubmit${url.suffix}", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO regSubmit(HttpServletRequest request,
			@RequestParam(value = "username", required = false , defaultValue="") String username,
			@RequestParam(value = "email", required = false , defaultValue="") String email,
			@RequestParam(value = "password", required = false , defaultValue="") String password,
			@RequestParam(value = "siteid", required = false , defaultValue="0") int siteid,
			@RequestParam(value = "classid", required = false , defaultValue="0") int classid,
			@RequestParam(value = "postid", required = false , defaultValue="0") int postid
			){
//		if(Global.getInt("ALLOW_USER_REG") == 0){
//			return error("抱歉，当前禁止用户自行注册开通网站！");
//		}
		
		
		
		//验证码校验
		BaseVO capVO = Captcha.compare(request.getParameter("code"), request);
		if(capVO.getResult() == BaseVO.FAILURE){
			ActionLogCache.insert(request, "论坛用户注册失败", "验证码出错，提交的验证码："+StringUtil.filterXss(request.getParameter("code")));
			return capVO;
		}
		
		if(siteid == 0){
			return error("siteid 不存在");
		}
		SystemSet systemSet = sqlService.findById(SystemSet.class, siteid);
		if(systemSet != null && systemSet.getIsReg() != null && systemSet.getIsReg() - SystemSet.IS_REG_NO == 0){
			return error("当前不开放注册！");
		}
		
		//注册用户
		User user = new User();
		user.setUsername(filter(username));
		user.setEmail(filter(email));
		user.setPassword(password);
		user.setOssSizeHave(0);
		user.setAuthority(com.xnx3.wangmarket.plugin.bbs.Global.BBS_USER_ROLE_ID+"");
		BaseVO userVO = userService.reg(user, request);
		if(userVO.getResult() - BaseVO.FAILURE == 0){
			return userVO;
		}
		
		//为此用户设置其自动登录成功
		int userid = Lang.stringToInt(userVO.getInfo(), 0);
		if(userid == 0){
			ActionLogCache.insert(request, "warn", "注册论坛出现问题，info:"+userVO.getInfo());
			return error(userVO.getInfo());
		}
		BaseVO loginVO = userService.loginByUserid(request,userid);
		if(loginVO.getResult() - BaseVO.FAILURE == 0){
			return loginVO;
		}
		
		//找到site，以便ue编辑器上传图片，上传到指定站点目录下
		UserBean userBean = new UserBean();
		userBean.setSite(sqlService.findById(Site.class, siteid));
		ShiroFunc.getCurrentActiveUser().setObj(userBean);
		ShiroFunc.getCurrentActiveUser().setUeUploadParam1(siteid+"");
		
		User u = getUser();
		Action.addAction(siteid, "<a href=\"home.do?siteid="+siteid+"&userid="+u.getId()+"\" target=\"_black\">"+u.getNickname()+"</a>注册为本论坛用户");
		
		return success(getSuccessJumpPage(siteid, classid, postid));
	}
	
	
	/**
	 * 登陆页面
	 */
	@RequestMapping("login${url.suffix}")
	public String login(HttpServletRequest request,Model model){
		//检测 MASTER_SITE_URL、 ATTACHMENT_FILE_URL 是否已经设置，即是否已经install安装了
//		if(Global.get("MASTER_SITE_URL") == null || Global.get("MASTER_SITE_URL").length() == 0 || Global.get("ATTACHMENT_FILE_URL") == null || Global.get("ATTACHMENT_FILE_URL").length() == 0){
//			return error(model, "监测到您尚未安装系统！请先根据提示进行安装", "install/index.do");
//		}
		
		if(getUser() != null){
			ActionLogCache.insert(request, "论坛已登陆", "已经登录，无需再登录，进行跳转");
			//重定向到论坛首页
			return redirect("plugin/bbs/list.do?siteid="+request.getParameter("siteid"));
		}
		
		ActionLogCache.insert(request, "进入论坛登录页面");
		modelSet(request, model);
		return "plugin/bbs/login";
	}

	/**
	 * 登陆请求验证
	 * @param request {@link HttpServletRequest} 
	 * 		<br/>登陆时form表单需提交三个参数：username(用户名/邮箱)、password(密码)、code（图片验证码的字符）
	 * @param siteid 跟随传第参数，此论坛是属于那个站点，必填，不会为空
	 * @param classid 分类id，来源是哪个板块，可为空
	 * @param postid 帖子id，来源是哪个帖子详情页面，可为空
	 * @return vo.result:
	 * 			<ul>
	 * 				<li>0:失败</li>
	 * 				<li>1:成功，成功后，info会返回跳转的链接地址，如： plugin/bbs/view.do?id=123</li>
	 * 			</ul>
	 */
	@RequestMapping("loginSubmit${url.suffix}")
	@ResponseBody
	public BaseVO loginSubmit(HttpServletRequest request,Model model,
			@RequestParam(value = "siteid", required = false , defaultValue="0") int siteid,
			@RequestParam(value = "classid", required = false , defaultValue="0") int classid,
			@RequestParam(value = "postid", required = false , defaultValue="0") int postid
			){
		//验证码校验
		BaseVO capVO = Captcha.compare(request.getParameter("code"), request);
		if(capVO.getResult() == BaseVO.FAILURE){
			ActionLogCache.insert(request, "论坛用户名密码模式登录失败", "验证码出错，提交的验证码："+StringUtil.filterXss(request.getParameter("code")));
			return capVO;
		}
	
		//验证码校验通过
		BaseVO baseVO =  userService.loginByUsernameAndPassword(request);
		if(baseVO.getResult() == BaseVO.SUCCESS){
			//登录成功,BaseVO.info字段将赋予成功后跳转的地址，所以这里要再进行判断
			
			//用于缓存入Session，用户的一些基本信息，比如用户的站点信息、用户的上级代理信息、如果当前用户是代理，还包含当前用户的代理信息等
			UserBean userBean = new UserBean();
			//找到site，以便ue编辑器上传图片，上传到指定站点目录下
			ShiroFunc.getCurrentActiveUser().setUeUploadParam1(siteid+"");
			userBean.setSite(sqlService.findById(Site.class, siteid));
			
			//得到当前登录的用户的信息
			User user = getUser();
			
			//将用户相关信息加入Shiro缓存
			ShiroFunc.getCurrentActiveUser().setObj(userBean);
			
			ActionLogCache.insert(request, "登陆论坛成功","登陆用户:"+request.getParameter("username"));
			
			//论坛的最新动作
			Action.addAction(siteid, "<a href=\"home.do?siteid="+siteid+"&userid="+user.getId()+"\" target=\"_black\">"+user.getNickname()+"</a>登陆成功");
			
			return success(getSuccessJumpPage(siteid, classid, postid));
		}else{
			ActionLogCache.insert(request, "用户名密码模式登录失败",baseVO.getInfo());
		}
		
		return baseVO;
	}
	
	/**
	 * 获取登陆成功、注册成功后跳转到的页面
	 * @param siteid 站点id，必须有的
	 * @param classid 论坛分类id，可为0
	 * @param postid 帖子id，可为0
	 * @return 返回如：  plugin/bbs/view.do?id=123
	 */
	private String getSuccessJumpPage(int siteid, int classid, int postid){
		if(postid > 0){
			//如果是从帖子详情来的，那么会先跳转帖子详情
			return "plugin/bbs/view.do?id="+postid;
		}else if (classid > 0) {
			//跳转到某个板块
			return "plugin/bbs/list.do?classid="+classid+"&siteid="+siteid;
		}else{
			//跳转到所有帖子页面
			return "plugin/bbs/list.do?siteid="+siteid;
		}
	}
	
	/**
	 * 用户退出
	 */
	@RequestMapping("logout${url.suffix}")
	@ResponseBody
	public BaseVO logout(Model model, HttpServletRequest request,
			@RequestParam(value = "siteid", required = false , defaultValue="0") int siteid){
		User user = getUser();
		Action.addAction(siteid, "<a href=\"home.do?siteid="+siteid+"&userid="+user.getId()+"\" target=\"_black\">"+user.getNickname()+"</a>注销登陆");
		
		ActionLogCache.insert(request, "论坛用户注销登录");
		userService.logout();
		
		return success();
	}
	
}
